
from whiff import gateway
from whiff import resolver
from whiff.middleware import misc
from whiff import whiffenv
import time

class addItem(misc.utility):
    
    def __init__(self, successPage, failurePage):
        self.successPage = successPage
        self.failurePage = failurePage
        
    def __call__(self, env, start_response):
        env = resolver.process_cgi(env, parse_cgi=True)
        name = whiffenv.cgiGet(env, "Name", "").strip()
        title = whiffenv.cgiGet(env, "Title", "").strip()
        summary = whiffenv.cgiGet(env, "Summary", "").strip()
        text = whiffenv.cgiGet(env, "Text", "").strip()
        note = whiffenv.cgiGet(env, "Note", "").strip()
        error_message = ""
        if not (name and title and summary and text):
            error_message = "please provide all required data: name, title, summary and text"
        is_stub = env.get("STUB")
        timeStamp = time.ctime()
        if not error_message:
            if is_stub:
                pass # stub: don't actually do the update
            else:
                self.insertItem(env, name, title, summary, text, note, timeStamp)
            return self.deliver_page(self.successPage, env, start_response)
        else:
            env["error_message"] = error_message
            return self.deliver_page(self.failurePage, env, start_response)

    def insertItem(self, env, name, title, summary, text, note, timeStamp):
        data = {}
        data["Name"] = name
        data["Title"] = title
        data["Summary"] = summary
        data["Text"] = text
        data["Note"] = note
        data["TimeStamp"] = timeStamp
        storage = gateway.getResource(env, ["storage"])
        if storage is None:
            storage = {}
        storage[name] = data
        gateway.putResource(env, ["storage"], storage)
    
__middleware__ = addItem
